/**
 * \file simon.c
 * \brief Mode du jeu simon
 * \author Nicolas M.
 * \version 0.2
 * \date 20 mars 2011
 *
 */
 
#include "simon.h"

#include "../utils/display.h"
#include "../utils/utils.h"

#include <msp430x14x.h>

#include <includes.h>
#include <stdlib.h>

#define BIP1_FREQ	225 
#define BIP2_FREQ	200
#define BIP3_FREQ	175
#define BIP4_FREQ	150

#define BIP_LENGHT	20
 
extern OS_EVENT *ButtonMbox;

void bip(int btn)
{
	int debut = OSTimeGet();
	int delayTic;
	switch(btn)
	{
		case COM_B1:
			delayTic = BIP1_FREQ;
			break;
		case COM_B2:
			delayTic = BIP2_FREQ;
			break;
		case COM_B3:
			delayTic = BIP3_FREQ;
			break;
		case COM_B4:
			delayTic = BIP4_FREQ;
			break;
	}
	while (OSTimeGet()-debut < BIP_LENGHT) 
	{
		P4OUT |= BIT3;
		delay(delayTic);
		P4OUT &= ~BIT3;
		delay(delayTic);
	}
}

/*
 * Joue la sequence
 */
void play(char *sequence, int size)
{
	int i =0;
	while (i < size)
	{
		afficherChar('V', LINE_2, (sequence[i]-1)*4+1);
		OSTimeDly(BIP_LENGHT);
		bip(sequence[i]);
		afficherChar(' ', LINE_2, (sequence[i]-1)*4+1);
		OSTimeDly(BIP_LENGHT);
		i++;
	}
}


/*
 * Emet un bip d'erreur et affiche le message "Rate !" à l'écran
 */
void playErrorBip()
{
	afficher("Rate !");
}

/*
 * Emet un bip de succès et affiche le message "Bien joue !" à l'écran
 */
void playSuccessBip()
{
	afficher("Bien joue !");
}

void simon()
{
	int tailleSequence, run=1, correct=1, currentIdx;
	unsigned int button, value;
	unsigned char *sequence;
	INT8U err;
	
	sequence = malloc(64*sizeof(unsigned char));
	tailleSequence = 0;

	afficher("Lancement du\nSimon");
	OSTimeDly(DELAY_1sec);
	afficher("Appui long sur\nB1 pour quitter");
	OSTimeDly(DELAY_1sec);
	while (run)
	{
		if (correct)
		{
			// Generation d'une valeur aleatoire entre 1 et 4
			sequence[tailleSequence] = TAR/5;
			sequence[tailleSequence] = sequence[tailleSequence]%4 + 1;
			tailleSequence++;
		}

		afficher("Ecoutez ...");
		OSTimeDly(BIP_LENGHT);
		play(sequence, tailleSequence);

		// Purge des boutons 
		while(OSMboxAccept(ButtonMbox) != 0);

		afficher("A votre tour !");
		currentIdx = 0;
		correct = 1;
		while(correct && currentIdx < tailleSequence && run)
		{
			button = OSMboxPend(ButtonMbox, 0, &err);
			if (button >= 1 && button <= 4)
			{
				bip(button);
				value = sequence[currentIdx];
				if(button == value)
				{
					currentIdx++;
				}
				else
				{
					correct = 0;
					playErrorBip();
				}
			}
			// Quitte le jeu
			if (button == COM_B1_LONG) run = 0;
		}
		if (correct && run) 
		{
			playSuccessBip();
		}
		OSTimeDly(BIP_LENGHT);
	}
	free(sequence);
}
